package cn.com.demo.keystore;

import cn.com.demo.cert.X509CertificateExample;
import cn.com.demo.util.Utils;

import javax.crypto.SecretKey;
import javax.security.auth.x500.X500PrivateCredential;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

public class JCEKSStoreEntryExample {
    public static char[] keyPassword = "endPassword".toCharArray();
    public static char[] secretKeyPassword = "secretPassword".toCharArray();

    public static KeyStore createKeyStore() throws Exception {
        KeyStore store = KeyStore.getInstance("JCEKS");

        //initialize
        store.load(null, null);

        X500PrivateCredential rootCredential = X509CertificateExample.generateRootCredetial();
        X500PrivateCredential interCredential = X509CertificateExample.generateIntermediateCredential(
                rootCredential.getPrivateKey(), rootCredential.getCertificate());
        X500PrivateCredential endCredential = X509CertificateExample.generateEndCredential(interCredential.getPrivateKey(),
                interCredential.getCertificate());

        X509Certificate[] chain = new X509Certificate[3];
        chain[0] = endCredential.getCertificate();
        chain[1] = interCredential.getCertificate();
        chain[2] = rootCredential.getCertificate();

        SecretKey key = Utils.generateKeyForAES(256, Utils.createFixedRandom());

        //set the entries
        store.setEntry(rootCredential.getAlias(),
                new KeyStore.TrustedCertificateEntry(rootCredential.getCertificate()),
                null);

        store.setEntry(endCredential.getAlias(),
                new KeyStore.PrivateKeyEntry(endCredential.getPrivateKey(), chain),
                new KeyStore.PasswordProtection(keyPassword));

        store.setEntry("secretkey",
                new KeyStore.SecretKeyEntry(key),
                new KeyStore.PasswordProtection(secretKeyPassword));


        return store;
    }

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        KeyStore store = createKeyStore();
        char[] password = "password".toCharArray();

        //save the store
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        store.store(bOut, password);

        //reload from scratch
        store = KeyStore.getInstance("JCEKS");
        store.load(new ByteArrayInputStream(bOut.toByteArray()), password);

        Enumeration<String> e = store.aliases();
        while (e.hasMoreElements()) {
            String alias = (String) e.nextElement();
            System.out.println("found " + alias
                    + ",isCertificate ? " + store.isCertificateEntry(alias)
                    + ",private key entry ? " + store.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)
                    + ",secret key entry ? " + store.entryInstanceOf(alias, KeyStore.SecretKeyEntry.class)
            );
        }
    }

}
